package com.cloudcross.ssp.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.cloudcross.ssp.base.dao.GenericIBatisDao;
import com.cloudcross.ssp.loader.AdvertiserLoader;

public class ApplicationListener implements ServletContextListener {

    private Logger logger = LogManager.getLogger(getClass());

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext());
        GenericIBatisDao myBatisDao = (GenericIBatisDao) context.getBean("iBatisDao");
        logger.debug("信息开始加载到内存");
        initAdvertiser(myBatisDao);// 初始化广告主代理商信息
        Thread thread = new Thread(UploadListener.getInstance());
        thread.start();
        logger.debug("信息加载完毕");
    }

    // 每次添加广告主就会重新调用该方法
    // 加载广告主信息
    public void initAdvertiser(GenericIBatisDao myBatisDao) {
        logger.debug("=====广告主信息开始加载=====");
        AdvertiserLoader.ADVERTISER_LIST = myBatisDao.getList("advertiserSqlMapper.queryAgentIdAndAdvertiserId");
        AdvertiserLoader.setAgentIdAdvertiserIdMap();
        logger.debug("=====广告主信息加载完成=====");
    }
}